;(function($) {
	$.widget('bpm.dashboard', {
		options: {
			rootUrl: null,
			rowSize: 37
		},
		
		_create: function() {
			var self = this,
				requiredParams = ['rootUrl'];
		
			$.each(requiredParams, function(index, param) {
				if (self.options[param] === null) {
					alert('Missing parameter: ' + param);
				}	
			});
			
			self._initParams();
			self._bindEvents();
			self._initPlugins();
			self._loadProductionDataTables();
		},

		_initParams: function() {
			var self = this;
			
			self.baseDataTableOptions = {
				"bProcessing" : true,
				"bServerSide" : true,
				"sServerMethod" : "POST",
				"bAutoWidth": false,
				"bFilter": false,
				"bLengthChange" : false,
				"bInfo": true,
				"bPaginate": true,
		        "iDisplayLength" : self._getDisplayLength(),
				"oLanguage": { 
					"sEmptyTable": $('<div>').append($.tableEmptyMessage).html(),
					"sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
				    "sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
				    "sInfoFiltered": "",
				    "sInfoPostFix":  "",
				    "sProcessing":   "Carregando...",
					"oPaginate": {
				        "sFirst":    "Primeiro",
				        "sPrevious": "Anterior",
				        "sNext":     "Próximo",
				        "sLast":     "Último"
				    }
				},
				"fnServerParams" : function(aoData) {
					$('#frmFilter select,input').each(function(index, elm) {
						switch (elm.type) {
							case 'checkbox':
							case 'radio':
								if (elm.checked) {
									aoData.push({"name" : elm.name, "value" : elm.value});
								}
								break;
							default:
								if (elm.name === 'refDate') {
									if (self._isValidDate(elm.value)) {
										aoData.push({"name" : elm.name, "value" : elm.value});
									}
								} else {
									aoData.push({"name" : elm.name, "value" : elm.value});
								}
								break;	
						}
					});
				},
				"fnDrawCallback": function(oSettings) {
					var $elm = $($('#' + oSettings.nTable.id + ' td.truncate:visible')[0]),
						width = $elm.width();
					
					if ($elm.length > 0) {
						$('td.truncate:visible').each(function(index, elm) {
							if ($elm.height() < $(elm).height()) {
								$elm = $(elm);
							}
						});
						
						var count = 0;
						while ($elm.height() > 21) {
							$('#' + oSettings.nTable.id + ' .truncate').textTruncate($elm.width() - 10);
							if (count++ > 10) break;
						}
					}
				}
			};
			
			// armazena as datatables
			self.productionTables = [];
			self.managerTables = [];
		},

		_bindEvents: function() {
			var self = this;
			
			$("#lateComponents").delegate("tbody tr", "click", function(event) {
				var data = self.dtLate.fnGetData(this);

				$('#mdl').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'orderComponent/view/' + data.order_component_id
				});
			});

			$("#onScheduleComponents").delegate("tbody tr", "click", function(event) {
				var data = self.dtOnSchedule.fnGetData(this);

				$('#mdl').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'orderComponent/view/' + data.order_component_id
				});
			});

			$("#aheadScheduleComponents").delegate("tbody tr", "click", function(event) {
				var data = self.dtAhead.fnGetData(this);

				$('#mdl').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'orderComponent/view/' + data.order_component_id
				});
			});

			$("#lateOrders").delegate("tbody tr", "click", function(event) {
				var data = self.dtLateOrders.fnGetData(this);

				$('#mdlManager').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'order/viewDetails/' + data.order_id
				});
			});

			$("#onScheduleOrders").delegate("tbody tr", "click", function(event) {
				var data = self.dtOnScheduleOrders.fnGetData(this);

				$('#mdlManager').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'order/viewDetails/' + data.order_id
				});
			});

			$("#aheadScheduleOrders").delegate("tbody tr", "click", function(event) {
				var data = self.dtAheadScheduleOrders.fnGetData(this);

				$('#mdlManager').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'order/viewDetails/' + data.order_id
				});
			});
			
			$("#executedOrders").delegate("tbody tr", "click", function(event) {
				var data = self.dtExecutedOrders.fnGetData(this);

				$('#mdlManager').removeData('bs.modal').modal({
					remote: self.options.rootUrl + 'order/viewDetails/' + data.id
				});
			});

			$("#menu-toggle").click(function(e) {
				e.preventDefault();
				$("#wrapper").toggleClass("active");
			});
			
			$('#btnFilter').click(function(e) {
				if ($('#refDate').val() === '') {
					$('#refDate').tooltip('hide');
					self.updateTables();
				} else {
					if (self._isValidDate($('#refDate').val())) {
						$('#refDate').tooltip('hide');
						self.updateTables();
					} else {
						$('#refDate').tooltip('show');
					}
				}

				e.preventDefault();
			});

			$('#btnReportManager').click(function(e) {
				var $elm = $(this);
				
				if (!$elm.hasClass('active')) {
					$('#btnReportProduction').removeClass('active');
					$elm.addClass('active');

					$('#productionRel').hide();
					$('#managerRel').show();

					$("#componentsGroup").hide();
					
					if (self.managerTables.length > 0) {
						self.updateTables();
					} else {
						self._loadManagerDataTables();
					}
				}

				e.preventDefault();
			});

			$('#btnReportProduction').click(function(e) {
				var $elm = $(this);
				
				if (!$elm.hasClass('active')) {
					$('#btnReportManager').removeClass('active');
					$elm.addClass('active');

					$('#managerRel').hide();
					$('#productionRel').show();

					$("#componentsGroup").show();
					
					if (self.productionTables.length > 0) {
						self.updateTables();
					} else {
						self._loadProductionDataTables();
					}
				}

				e.preventDefault();
			});
			
			$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {				
				var $elm = $($('td.truncate:visible')[0]);
				
				if ($elm.length > 0) {
					$('td.truncate:visible').each(function(index, elm) {
						if ($elm.height() < $(elm).height()) {
							$elm = $(elm);
						}
					});
					
					var count = 0;
					while ($elm.height() > 21) {
						$('td.truncate:visible').textTruncate($elm.width() - 10);
						if (count++ > 10) break;
					}
				}
			});
			
			$('#btnReset').click(function(e) {
				$('input').val('');
				$('#customerId').select2('val', '');
				$('#accessory').select2('val', '');
				$('#costsCentresId').select2('val', '');
				$('#allCC')[0].checked = true;
				
				e.preventDefault();
			});
		},

		_initPlugins: function() {
			$('.input-group.date input').datepicker({
				minDate: new Date(),
				onClose: function() {
					$('#refDate').tooltip('hide');
				}
			})
			
			$('.input-group .input-group-addon').click(function(){
				$('.input-group.date input').datepicker().focus();
			});
			
			$('.input-group.date input').mask('99/99/9999');

			$('#customerId').select2({
				allowClear: true,
				placeholder: 'Todos os clientes'
			});
			
			$('#accessory').select2({
				allowClear: true,
				placeholder: 'Todos os tipos'
			});
			
			$('#costsCentresId').select2({
				allowClear: true,
				placeholder: 'Todos'
			});
			
			$('#refDate').tooltip({
				placement: 'bottom',
				title: 'Data inválida',
				trigger: 'manual'
			});
		},

		_loadProductionDataTables: function() {
			var self = this;
	
			var dtLateComponents = self.baseDataTableOptions;
			dtLateComponents.sAjaxSource = self.options.rootUrl + 'orderComponent/late';
			dtLateComponents.aoColumns = [
				{
					"sTitle": "Cod CIGAM",
					"mDataProp": "code",
					"bSortable" : false
				},
				{
					"sTitle": "Ordem",
	            	"mDataProp": "production_number",
	            	"bSortable" : false,
	            	"sClass": "centered"
	            },
	            {
					"sTitle": "Cliente",
	            	"mDataProp": "customer_name",
	            	"bSortable" : false,
	            	"sClass": "truncate"
	            },
	            {
					"sTitle": "Qtd",
	            	"mDataProp": 'order_amount',
	            	"bSortable" : false,
	            	"fnRender": function(obj, value) {
	            		if (obj.aData.order_amount != null && obj.aData.component_amount) {
	            			return obj.aData.order_amount * obj.aData.component_amount;
	            		}
	            		
	            		return '';
	            	}
	            },
				{
					"sTitle": "Item",
	            	"mDataProp": "component_name",
	            	"bSortable" : false,
	            	'sClass': 'truncate'
	            },
	            {
	            	"sTitle": "C.Custo Atual",
	            	"mDataProp": "actual_costs_centre_name",
	            	"bSortable" : false,
	            	"sClass": "centered"
	            },
	            {
	            	"sTitle": "Saída Prevista",
	            	"mDataProp": "probable_date",
	            	"bSortable" : false,
	            	"sClass": "centered",
	            	"fnRender": function (obj, value) {
	            		return value.split('-').reverse().join('/');
	            	}
	            },
	            {
	            	"sTitle": "C.Custo Previsto",
	            	"mDataProp": "probable_cc_name",
	            	"bSortable" : false,
	            	"sClass": "centered visible-lg"
	            }
			];

			self.dtLate = $('#lateComponents').dataTable(dtLateComponents);
			self.productionTables.push(self.dtLate);

			var dtOnScheduleComponents = self.baseDataTableOptions;
			dtOnScheduleComponents.sAjaxSource = self.options.rootUrl + 'orderComponent/on-schedule';
			dtOnScheduleComponents.aoColumns = [
				{
					"sTitle": "Cod CIGAM",
					"mDataProp": "code",
					"bSortable" : false
				},
				{
					"sTitle": "Ordem",
					"mDataProp": "production_number",
					"bSortable" : false,
					"sClass": "centered"
				},
				{
					"sTitle": "Cliente",
	            	"mDataProp": "customer_name",
	            	"bSortable" : false,
	            	"sClass": "truncate"
	            },
	            {
					"sTitle": "Qtd",
	            	"mDataProp": "order_amount",
	            	"bSortable" : false,
	            	"fnRender": function(obj, value) {
	            		if (obj.aData.order_amount != null && obj.aData.component_amount) {
	            			return obj.aData.order_amount * obj.aData.component_amount;
	            		}
	            		
	            		return '';
	            	}
	            },
				{
	            	"sTitle": "Item",
	                "mDataProp": "component_name",
	                "bSortable" : false,
	                "sClass": 'truncate'
				},
	            {
	            	"sTitle": "C.Custo Atual",
	                "mDataProp": "actual_costs_centre_name",
	                "bSortable" : false,
	                "sClass": "centered"
				},
	            {
	            	"sTitle": "Entrada",
	                "mDataProp": "previous_probable_date",
	                "bSortable" : false,
	                "sClass": "centered",
	                "fnRender": function (obj, value) {
	                	return value.split('-').reverse().join('/');
					}
				},
				{
	            	"sTitle": "Saída",
	                "mDataProp": "probable_date",
	                "bSortable" : false,
	                "sClass": "centered",
	                "fnRender": function (obj, value) {
	                	return value.split('-').reverse().join('/');
					}
				}
			];

			self.dtOnSchedule = $('#onScheduleComponents').dataTable(dtOnScheduleComponents);
			self.productionTables.push(self.dtOnSchedule);

			var dtAheadScheduleComponents = self.baseDataTableOptions;
			dtAheadScheduleComponents.sAjaxSource = self.options.rootUrl + 'orderComponent/ahead-schedule';
			dtOnScheduleComponents.aoColumns = [
				{
					"sTitle": "Cod CIGAM",
					"mDataProp": "code",
					"bSortable" : false
				},
				{
					"sTitle": "Ordem",
					"mDataProp": "production_number",
					"bSortable" : false,
					"sClass": "centered"
				},
				{
					"sTitle": "Cliente",
	            	"mDataProp": "customer_name",
	            	"bSortable" : false,
	            	"sClass": "truncate"
	            },
	            {
					"sTitle": "Qtd",
	            	"mDataProp": "order_amount",
	            	"bSortable" : false,
	            	"fnRender": function(obj, value) {
	            		if (obj.aData.order_amount != null && obj.aData.component_amount) {
	            			return obj.aData.order_amount * obj.aData.component_amount;
	            		}
	            		
	            		return '';
	            	}
	            },
	        	{
	            	"sTitle": "Item",
	                "mDataProp": "component_name",
	                "bSortable" : false,
	                "sClass": 'truncate'
				},
	            { 
	            	"sTitle": "C.Custo Previsto", 
	                "mDataProp": "probable_cc_name", 
	                "bSortable" : false,
	                "sClass": "centered"
				},
				{ 
	            	"sTitle": "Saída", 
	                "mDataProp": "probable_date", 
	                "bSortable" : false,
	                "sClass": "centered visible-lg",
	                "fnRender": function (obj, value) {
	                	return value.split('-').reverse().join('/');
					}
				},
				{ 
	            	"sTitle": "C.Custo Atual", 
	                "mDataProp": "actual_costs_centre_name", 
	                "bSortable" : false,
	                "sClass": "centered"
				}
				
			];
	
			self.dtAhead = $('#aheadScheduleComponents').dataTable(dtAheadScheduleComponents);
			self.productionTables.push(self.dtAhead);
		},

		_loadManagerDataTables: function() {
			var self = this,
				dtOptions = self.baseDataTableOptions;

			dtOptions.aoColumns = [
				{ 
					"sTitle": "Pedido",
	            	"mDataProp": "order_number", 
	            	"bSortable" : false
	            },
	            { 
					"sTitle": "Ordem", 
					"mDataProp": "production_number", 
					"bSortable" : false,
					"sClass": "centered"
				},
	            { 
					"sTitle": "Cliente", 
	            	"mDataProp": "customer_name", 
	            	"bSortable" : false,
	            	"sClass": 'truncate'
	            },
	            { 
	            	"sTitle": "Início", 
	                "mDataProp": "production_start_date", 
	                "bSortable" : false,
	                "sClass": "centered",
	                "fnRender": function (obj, value) {
	                	return value.split('-').reverse().join('/');
					}
				},
				{ 
	            	"sTitle": "Entrega Prevista", 
	                "mDataProp": "production_end_date", 
	                "bSortable" : false,
	                "sClass": "centered",
	                "fnRender": function (obj, value) {
	                	return value.split('-').reverse().join('/');
					}
				}
			];

			// atrasados
			dtOptions.sAjaxSource = self.options.rootUrl + 'orderComponent/late-orders';
			
			self.dtLateOrders = $('#lateOrders').dataTable(dtOptions);
			self.managerTables.push(self.dtLateOrders);

			// em dia
			dtOptions.sAjaxSource = self.options.rootUrl + 'orderComponent/on-schedule-orders';
			
			self.dtOnScheduleOrders = $('#onScheduleOrders').dataTable(dtOptions);
			self.managerTables.push(self.dtOnScheduleOrders);

			// adiantados
			dtOptions.sAjaxSource = self.options.rootUrl + 'orderComponent/ahead-schedule-orders';
			
			self.dtAheadScheduleOrders = $('#aheadScheduleOrders').dataTable(dtOptions);
			self.managerTables.push(self.dtAheadScheduleOrders);
			
			// concluídos
			dtOptions.sAjaxSource = self.options.rootUrl + 'order/executedList';
			dtOptions.aoColumns.push({
            	"sTitle": "Entrega Real", 
                "mDataProp": "production_real_end_date", 
                "bSortable" : false,
                "sClass": "centered",
                "fnRender": function (obj, value) {
                	var dateArray = value.split(' '),
                		date = dateArray[0].split('-').reverse().join('/');
                	
                	return date + ' ' + dateArray[1];
                	
				}
			});
			
			self.dtExecutedOrders = $('#executedOrders').dataTable(dtOptions);
			self.managerTables.push(self.dtExecutedOrders);
		},
		
		_getDisplayLength: function() {
			var self = this,
				discountSpace = 290;
				rowMediumSize = self.options.rowSize;
				viewArea = $('body').height();
				rowSpace = viewArea - discountSpace;
			
			return Math.floor(rowSpace / rowMediumSize);
		},
		
		_isValidDate: function validDate(text) {
		    var comp = text.split('/');

		    if (comp.length !== 3) {
		        return false;
		    }

		    var d = parseInt(comp[0], 10);
		    var m = parseInt(comp[1], 10);
		    var y = parseInt(comp[2], 10);
		    var date = new Date(y, m - 1, d);
		    
		    var isValid = (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d);
		    
		    if (isValid) {
		    	var currentDate = new Date();
		    	currentDate.setHours(0);
				currentDate.setMinutes(0);
				currentDate.setSeconds(0);
				currentDate.setMilliseconds(0);
				
				if (date.getTime() < currentDate.getTime()) {
					return false;
				}
				
				return true;
		    }
		    
		    return false;
		},

		updateTables: function() {
			var self = this,
				tables;

			if ($('#btnReportProduction').hasClass('active')) {
				tables = self.productionTables;
			} else {
				tables = self.managerTables;
			}

			$.each(tables, function(index, dataTable) {
				dataTable.fnDraw();
			});
		}
	});
})(jQuery);